<template>
  <div>
    <el-dialog
      top="80px"
      width="70%"
      append-to-body
      :visible.sync="visible"
      :before-close="hanldClose"
      :close-on-click-modal="false"
    >
      <div v-for="(item, index) in eleData" :key="index">
        <div class="mb-3">
          <el-echarts
            theme="macarons"
            :height="400"
            @onInit="c => onInit(c, index)"
            v-show="!imgType"
            :option="item.option"
          ></el-echarts>
          <img height="400" class="w-100" v-show="imgType" :src="item.imgData" alt="" />
        </div>
        <table class="table table-bordered table-border-black">
          <tbody>
            <tr>
              <td>表号</td>
              <td>{{ item.ele_table_no }}</td>
              <td>户名</td>
              <td>{{ item.ele_table_account }}</td>
            </tr>
            <tr>
              <td>地址</td>
              <td>{{ item.ele_table_address }}</td>
              <td>联系电话</td>
              <td>{{ item.ele_table_phone }}</td>
            </tr>
          </tbody>
        </table>

        <table class="table table-bordered table-border-black text-center">
          <tbody>
            <tr>
              <td>年月</td>
              <td>电费</td>
              <td>同比增长</td>
              <td>电量</td>
              <td>同比增长</td>
            </tr>
            <tr v-for="(fee, j) in item.eleFee" :key="`fee-${j}`">
              <td>{{ fee.ele_date }}</td>
              <td>{{ fee.ele_fee }}</td>
              <td>{{ fee.fee_compare }}</td>
              <td>{{ fee.ele_amount }}</td>
              <td>{{ fee.ele_amount_compare }}</td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="dl-wrap">
        <div class="dl-dt">用电情况</div>
        <div class="dl-dd">
          <el-radio v-model="postData.visit_status" label="1">正常</el-radio>
          <el-radio v-model="postData.visit_status" label="0">异常</el-radio>
        </div>
        <div class="dl-dd">
          <el-button type="primary" @click="submit('credit', 'credit_visit_record')">
            保存
          </el-button>
        </div>
      </div>

      <div class="report-action">
        <el-button type="primary" @click="hanldClose">
          <i class="fa fa-angle-left"></i>
          返回
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { echartsXFormatter } from '@vimi/utils-tool'
const visdate = new Date().toLocaleDateString()
export default {
  props: {
    visible: Boolean,
    imgType: Boolean,
    relatedData: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      related: {},
      eleData: {},
      postData: {},
      saveLoading: false,
    }
  },
  watch: {
    relatedData: {
      handler: function (val) {
        if (val.customer_related_id) {
          this.related = { ...val }
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    this.initRelated()
    this.powerData()
  },
  computed: {
    user() {
      return this.$store.getters.user
    },
  },
  methods: {
    async powerData() {
      const [res] = await this.$utils.promise(
        this.$api.getData('credit', 'datum_customer_ele_table', {
          'customer_related_id.eq': this.related.customer_related_id,
        })
      )

      if (res && res.data) {
        this.eleData = res.data.map(item => {
          item.eleFee = []
          item.option = null
          item.imgData = ''
          item.chart = null
          return item
        })
        for (const d of this.eleData) {
          this.$api
            .getData(
              'credit',
              'datum_customer_ele_fee',
              {
                'credit_ele_table_id.eq': d.credit_ele_table_id,
              },
              { ele_date: 'desc' }
            )
            .then(res => {
              if (res && res.data) {
                d.eleFee = res.data || []
                const xData = []
                const aData = []
                const bData = []
                const ascData = [...d.eleFee]
                ascData.sort((a, b) => (a.ele_date > b.ele_date ? 1 : -1))
                for (let t of ascData) {
                  xData.push(t.ele_date)
                  const fee = Number.parseFloat(t.ele_fee)
                  const nowFee = isNaN(fee) ? 0 : fee
                  aData.push(nowFee)
                  const compare = Number.parseFloat(t.fee_compare.replace(/(.*)%$/, '$1'))
                  // const lastFee = isNaN(compare) ? '-' : Math.round(nowFee * (1 + compare / 100) * 100) / 100
                  const lastFee = isNaN(compare)
                    ? '-'
                    : (Math.round(nowFee / (1 + compare / 100)) * 100) / 100
                  bData.push(lastFee)
                }

                d.option = {
                  backgroundColor: '#eff8fe',
                  title: {
                    text: '电费明细',
                    subtext: '',
                    left: 'center',
                  },
                  tooltip: {
                    trigger: 'axis',
                  },
                  legend: {
                    top: 32,
                    data: ['今年', '上年同期'],
                  },
                  xAxis: [
                    {
                      type: 'category',
                      data: xData,
                      axisLabel: {
                        formatter: v => echartsXFormatter(v, 5),
                      },
                    },
                  ],
                  yAxis: [
                    {
                      type: 'value',
                      name: '电费使用',
                    },
                  ],
                  series: [
                    {
                      name: '今年',
                      type: 'line',
                      data: aData,
                    },
                    {
                      name: '上年同期',
                      type: 'line',
                      data: bData,
                    },
                  ],
                }

                if (this.id && d.chart && d.chart.getDataURL) {
                  d.chart.on('finished', () => {
                    d.imgData = d.chart.getDataURL()
                  })
                }
              }
            })
        }
      }
    },
    async submit(service, tableName) {
      let data = {}
      data.customer_id = this.related.customer_id
      data.customer_name = this.related.customer_name
      data.customer_related_id = this.related.customer_related_id
      data.visit_person = this.user.realName
      data.visit_date = this.$utils.dateFormat(visdate, 'yyyy.MM.dd')
      data.visit_des = this.postData.visit_status === '1' ? '用电情况:正常' : '用电情况:异常'
      data.visit_type = '2'
      this.saveLoading = true
      const [res, err] = await this.$utils.promise(this.$api.addData(service, tableName, data))
      this.saveLoading = false
      if (res) {
        this.$message.success('数据采集成功！')
        this.hanldClose()
        this.$emit('success', true)
      } else {
        this.$message.error(`数据采集失败，请重试！（${err.status}）`)
      }
    },
    onInit(chart, index) {
      this.eleData[index].chart = chart
    },
    initRelated() {
      if (this.related.customer_related_id) {
        return
      }
      this.related = JSON.parse(sessionStorage.getItem('customer_related_view'))
    },
    hanldClose() {
      this.$emit('update:visible', false)
    },
  },
}
</script>

<style scoped></style>
